<?php
/**
 * Created by PhpStorm.
 * User: z-benjamin
 * Date: 16/9/9
 * Time: 上午11:49
 */

namespace lite\models\user;

use common\libs\Pagination;
use common\models\user\AR\BalanceRecordAR;
use lite\models\Weixin;
use Yii;
use lite\libs\CommonModel;
use lite\models\user\AR\UserAR;

class User extends CommonModel {


    public function checkAccessToken($user_id) {
        $user = UserAR::findOne(['id' => $user_id]);
        if(empty($user_id)) {
            return false;
        }
        return true;
    }

    public function register($loginUser) {
        $user = UserAR::findOne(['name' => $loginUser['username']]);

        if($user) {
            $this->setError(-1, "用户名已存在!");
            return false;
        }
        $user = UserAR::findOne(['mobile' => $loginUser['mobile']]);
        if($user) {
            $this->setError(-1, "该手机号已注册!");
            return false;
        }
        $user = new UserAR();
        $user->name = $loginUser['username'];
        $user->mobile = $loginUser['mobile'];
        $user->password = md5(md5($loginUser['password']));
        $user->status = 1;
        $res = $user->save();
        if($res) {
            return $user;
        } else {
            $this->setError(-1, "保存用户信息失败!");
            return false;
        }
    }

    public function saveUser($userInfo){

    }

    public function login($username, $password) {
        $user = UserAR::find()->andWhere(['name' => $username])->orWhere(['mobile' => $username])->one();
        if($user) {
            if($user->password !== md5(md5($password))) {
                $this->setError(-1, "用户名或密码错误");
                return false;
            }
            if($user->status == 0) {
                $this->setError(-998, "该账号已被禁用");
                return false;
            }
            $user->access_token = md5("LV" . time());
            $user->login_time = date('Y-m-d H:i:s');
            $user->expire = date('Y-m-d H:i:s', strtotime('+1 day'));
            $res = $user->save();
            if($res) {
                unset($user->password);
                unset($user->paypassword);
                return $user;
            } else {
                $this->setError(-1, "保存用户信息失败!");
                return false;
            }
        } else {
            $this->setError(-1, "用户名或密码错误!");
            return false;
        }
    }

    public function getUserById($userId) {
        $user = UserAR::find()->select("access_token,avatar,balance,birthday,comment,email,expire,id,is_leader,leader_code,leader_id,login_time,mobile,name,nickname,sex,status")->andWhere(['id' => $userId])->one();
        if(!$user) {
            $this->setError(-1, "异常的用户信息");
            return false;
        }
        return $user;
    }

    public function applyStar($userId) {
        $user = UserAR::find()->andWhere(['id' => $userId])->one();
        if(!$user) {
            $this->setError(-1, "异常的用户信息");
            return false;
        }

        if($user->status == 0) {
            $this->setError(-1, "账户状态异常");
            return false;
        }
        if($user->is_leader > 0) {
            $this->setError(-1, "您已经是旅游达人");
            return false;
        }
        if(!$user->weixin_openid) {
            $this->setError(-1, "您还未通过微信登录");
            return false;
        }

        //判断用户是否关注公众号
        $weixin = new Weixin();
        $weixinUser = $weixin->getUserInfo($user->weixin_openid);
        if(!$weixinUser['subscribe']) {
            $this->setError(-1, "只有关注<<悠长假期旅行网>>公众号的用户才能申请成为旅行达人");
            return false;
        }

        //获取微信二维码ticket
        $dbTrans = Yii::$app->db->beginTransaction();
        try {
            $qrcodeResult = $weixin->getQrcodeTicket('QR_SCENE', 1);
            $qrcodeAR = new QrcodeAR();
            $qrcodeAR->user_id = $user->id;
            $qrcodeAR->scene_id = 1;
            $qrcodeAR->ticket = $qrcodeResult['ticket'];
            $qrcodeAR->url = $qrcodeResult['url'];
            $qrcodeSaveResult = $qrcodeAR->save();
            if(!$qrcodeSaveResult) {
                throw new \Exception("保存二维码信息失败");
            }
            $user->is_leader = 1;
            $user->leader_code = strtolower(md5(time()));
            $user->regist_leader_time = date("Y-m-d H:i:s");
            $saveUserResult = $user->save();
            if(!$saveUserResult) {
                throw new \Exception("保存用户信息失败");
            }
            $dbTrans->commit();
        } catch(\Exception $e) {
            $dbTrans->rollback();
            $this->errMsg = $e->getMessage();
            return false;
        }

        return $user->toArray();
    }

    public function getQrcode($user_id) {
        $qrcode = QrcodeAR::findOne(['user_id' => $user_id]);
        if(!$qrcode) {
            $this->setError(-1, "不存在用户的推广二维码");
            return false;
        }
        return $qrcode;

    }

    public function getFriends($user_id, $offset = 0, $limit = 20) {
        $query = UserAR::find()->select("id,leader_id,avatar,nickname,sex,reg_time")->where(['leader_id' => $user_id]);
        $count = $query->count();
        // create a pagination object with the total count
        $pagination = new Pagination(['totalCount' => $count, 'perPage' => $limit, 'limit' => $limit,
                                      'offset' => $offset]);
        // limit the query using the pagination and retrieve the articles
        $users = $query->offset($pagination->offset)->limit($pagination->limit)->orderBy('id desc')->all();
        return array('list' => $users, 'pages' => $pagination);
    }

    public function getAwardRecords($user_id,$filters = array(),$offset=0,$limit){
        $query = BalanceRecordAR::find()->where(['user_id' => $user_id]);
        if($filters){
            foreach($filters as $filter){
                $query->andWhere($filter);
            }
        }
        $count = $query->count();
        // create a pagination object with the total count
        $pagination = new Pagination(['totalCount' => $count, 'perPage' => $limit, 'limit' => $limit,
                                      'offset' => $offset]);
        // limit the query using the pagination and retrieve the articles
        $users = $query->offset($pagination->offset)->limit($pagination->limit)->orderBy('id desc')->all();
        return array('list' => $users, 'pages' => $pagination);
    }
}